package com.team7.sso.service.impl;

import com.alibaba.fastjson.JSON;
import com.team7.sso.entity.Member;
import com.team7.sso.feign.MemberFeign;
import com.team7.sso.service.MemberService;
import com.team7.sso.vo.CommonResult;
import com.team7.sso.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class MemberServiceImpl implements MemberService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberFeign memberFeign;


    @Override
    public CommonResult loginByMobileAndPassword(LoginVo loginVo) {
        Member member = memberFeign.findStudentBymobile(loginVo.getMobile());
        HashMap<String, Object> map = new HashMap<>();
        if (member!=null){
            String password = new Md5Hash(loginVo.getQianPassword(), member.getSalt(), 1024).toString();
            if (password.equals(member.getPassword())&&member.getIsDisabled().equals(false)){//如果相同且未禁用，，则登录成功
                //1.数据存入redis中
                String key = UUID.randomUUID().toString().replace("-", ""); //生产钥匙，
                redisTemplate.opsForValue().set(key, JSON.toJSONString(member),24, TimeUnit.HOURS);

                //2.判断是讲师还是会员
                map.put("isTeacher",member.getIsType());
                //3.将redis中的key返回前台
                map.put("homeToken",key);
                map.put("mobile",loginVo.getMobile());
                map.put("memberId",member.getId());

                return new CommonResult(2000,"登录成功",map);
            }
            return new CommonResult(4000,"密码错误",null);

        }
        return new CommonResult(5000,"用户不存在",null);
    }

}
